package com.atguigu.gulimall.member.intercepter;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 订单服务模块-所有操作都需要登陆
 * 登陆拦截
 *
 * @Author ShiJieLin
 * @Date 2022/4/29 21:07
 * @Version 1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    /**
     * 做操作之前都需要查看是否登陆
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match) {
            return true;
        }
        HttpSession session = request.getSession();
        // 从redis中的session获取登陆信息
        MemberResponseVo memberResponseVo = (MemberResponseVo) session.getAttribute(
                AuthServerConstant.LOGIN_USER);

        if (null != memberResponseVo) {
            loginUser.set(memberResponseVo);
            return true;
        } else {
            session.setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
